package com.cskaoyan.servlet;

import com.cskaoyan.service.UserService;
import com.cskaoyan.service.UserServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author stone
 * @date 2021/11/22 10:12
 */
public class HelloServlet extends HttpServlet {

    //UserService userService = new UserServiceImpl();
    UserService userService;// = applicationContext.getBean(UserService.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ApplicationContext applicationContext = (ApplicationContext) getServletContext().getAttribute("applicationContext");
        userService = applicationContext.getBean(UserService.class);
        userService.sayHello();
        resp.getWriter().append("hello world");

        //根据url分发到不同的方法来处理请求
    }

    public void register(){

    }

    public void login(){}
    public void logout(){}

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    public void init() throws ServletException {
        if (getServletContext().getAttribute("applicationContext") != null) {
            return;
        }
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();
        //super.init();
        getServletContext().setAttribute("applicationContext",applicationContext);
    }
}
